﻿using System;
using System.Web.UI.WebControls;
using umbraco;
using umbraco.cms.businesslogic.datatype;
using umbraco.interfaces;
using umbraco.editorControls;

namespace Auros.Categorisation.Umbraco
{
    public class CategoryTreePreValueEditor : PreValueEditorBase
    {
        /// <summary>
        /// An object to temporarily lock writing to the database.
        /// </summary>
        private static readonly object m_Locker = new object();

        protected CategoryPicker Category { get; set; }

        public CategoryTreePreValueEditor(umbraco.cms.businesslogic.datatype.BaseDataType dataType) : base(dataType)
		{
		}

        public int RootCategoryID
        {
            get
            {
                var vals = PreValues.GetPreValues(this.DataType.DataTypeDefinitionId);

                if (vals.Count > 0)
                {
                    int id = 0;

                    int.TryParse(((PreValue)vals[0]).Value, out id);

                    return id;
                }
                else
                {
                    // return default
                    return 0;
                }
            }
        }

        public override void Save()
        {
            this.DataType.DBType = umbraco.cms.businesslogic.datatype.DBTypes.Nvarchar;

            lock (m_Locker)
            {
                var vals = PreValues.GetPreValues(this.DataType.DataTypeDefinitionId);

                if (vals.Count >= 1)
                {
                    // update
                    ((PreValue)vals[0]).Value = this.Category.Value;

                    ((PreValue)vals[0]).Save();
                }
                else
                {
                    // insert
                    PreValue.MakeNew(this.DataType.DataTypeDefinitionId, this.Category.Value);
                }
            }
        }

        protected override void CreateChildControls()
        {
            base.CreateChildControls();

            this.Category = new CategoryPicker(this.RootCategoryID.ToString());
            this.Category.Value = this.RootCategoryID.ToString();

            this.Controls.AddPrevalueControls(this.Category);
        }

        protected override void RenderPreValueProperties(System.Web.UI.HtmlTextWriter writer)
        {
            writer.AddPrevalueRow("Root Category:", "Select the category which is to be used as the root for this category selection data type.", this.Category);
        }

        public override System.Web.UI.Control Editor
        {
            get { return this; }
        }
    }

}